package wiki.hitime.stl.daq.manager;

import wiki.hitime.stl.daq.bean.db.DaqMsgRecord;
import wiki.hitime.stl.daq.bean.db.DaqMsgRule;
import wiki.hitime.stl.daq.enums.ProcessStatusEnum;
import wiki.hitime.stl.daq.mapper.DaqMsgRecordMapper;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangdaoping
 * @create 2019-07-17 14:39
 */
@Service
public class DaqMsgRecordManager {

    @Resource
    private DaqMsgRecordMapper daqMsgRecordMapper;

    /**
     * 添加未处理记录
     *
     * @param msgRule 规则信息
     * @return 记录id
     */
    public long addNotProcessRecord(Long executeRecordId, DaqMsgRule msgRule, Long checkRecordId, String msgContent) {
        DaqMsgRecord msgRecord = DaqMsgRecord.builder()
                .executeRecordId(executeRecordId)
                .checkRecordId(checkRecordId)
                .msgRuleId(msgRule.getId())
                .msgType(msgRule.getMsgType())
                .msgContent(msgContent)
                .notifyTime(DateTime.now().toDate())
                .processStatus(ProcessStatusEnum.WAITING.getStatus())
                .ctlVersion(msgRule.getCtlVersion())
                .build();
        daqMsgRecordMapper.insertSelective(msgRecord);
        return msgRecord.getId();
    }

    /**
     * 更新记录为处理成功
     *
     * @param recordId 记录编号
     */
    public void updateProcessSucceed(Long recordId) {
        DaqMsgRecord msgRecord = DaqMsgRecord.builder()
                .id(recordId)
                .processStatus(ProcessStatusEnum.SUCCEED.getStatus())
                .build();
        daqMsgRecordMapper.updateByPrimaryKeySelective(msgRecord);
    }

    /**
     * 更新记录为处理失败
     *
     * @param recordId 记录编号
     */
    public void updateProcessFailed(Long recordId, String processMsg) {
        processMsg = processMsg.length() > 2000 ? processMsg.substring(0, 2000) : processMsg;
        DaqMsgRecord msgRecord = DaqMsgRecord.builder()
                .id(recordId)
                .processStatus(ProcessStatusEnum.FAILED.getStatus())
                .processMsg(processMsg)
                .build();
        daqMsgRecordMapper.updateByPrimaryKeySelective(msgRecord);
    }

    /**
     * 根据执行记录编号集合获取消息记录集合
     *
     * @param executeRecordIdList
     * @return
     */
    public List<DaqMsgRecord> list(List<Long> executeRecordIdList) {
        if (CollectionUtils.isEmpty(executeRecordIdList)) {
            return new ArrayList<>();
        }
        Example selectExample = new Example(DaqMsgRecord.class, true, true);
        selectExample.createCriteria().andIn("executeRecordId", executeRecordIdList).andEqualTo("isDelete", Boolean.FALSE);
        return daqMsgRecordMapper.selectByExample(selectExample);
    }
}
